import React, { useState,useEffect } from 'react';
import { 
  Layout, 
  Menu, 
  Card, 
  Input, 
  Space,
  Dropdown,
  Badge,
  Typography,
  Breadcrumb,
  Result,
  Button
} from 'antd';
import {
  HomeOutlined,
  BookOutlined,
  ShoppingCartOutlined,
  UserOutlined,
  TeamOutlined,
  SolutionOutlined,
  FileTextOutlined,
  GiftOutlined,
  SettingOutlined,
  BellOutlined,
  UserAddOutlined,
  DownOutlined,
  CalendarOutlined,
} from '@ant-design/icons';
import { message } from 'antd';
import styles from './Houtai.module.css';

import Student from './component/Student'
import Course from './component/Course'
import Teacher from './component/Teacher'
import Order from './component/Order'
import OrderManagement from './component/OrderManagement'
import Dashboard from './component/Dashboard'
import SystemSettings from './component/SystemSettings'
import Schedule from './component/Schedule'
import PermissionGuard, { getUserPermissions, checkPagePermission } from './component/PermissionGuard'

const { Header, Sider, Content } = Layout;
const { SubMenu } = Menu;
const { Search } = Input;
const { Title } = Typography;

// 定义内容类型
const CONTENT_TYPES = {
  HOME: 'home',
  COURSE: 'course',
  STUDENT: 'student',
  TEACHER: 'teacher',
  ORDERS: 'orders',
  REFUNDS: 'refunds',
  BANNER: 'banner',
  ARTICLE: 'article',
  FLASH_SALE: 'flash-sale',
  COUPON: 'coupon',
  SETTINGS: 'settings',
  SCHEDULE: 'schedule'
};

// 定义面包屑映射
const BREADCRUMB_MAP = {
  [CONTENT_TYPES.HOME]: { name: '首页', path: ['首页'] },
  [CONTENT_TYPES.COURSE]: { name: '课程管理', path: ['首页', '课程管理'] },
  [CONTENT_TYPES.STUDENT]: { name: '学员管理', path: ['首页', '用户管理', '学员'] },
  [CONTENT_TYPES.TEACHER]: { name: '讲师管理', path: ['首页', '用户管理', '讲师'] },
  [CONTENT_TYPES.ORDERS]: { name: '订单管理', path: ['首页', '订单管理', '订单'] },
  [CONTENT_TYPES.REFUNDS]: { name: '退款管理', path: ['首页', '订单管理', '退款'] },
  [CONTENT_TYPES.BANNER]: { name: '轮播图管理', path: ['首页', '资讯管理', '轮播图'] },
  [CONTENT_TYPES.ARTICLE]: { name: '文章管理', path: ['首页', '资讯管理', '文章'] },
  [CONTENT_TYPES.FLASH_SALE]: { name: '秒杀活动', path: ['首页', '促销管理', '秒杀活动'] },
  [CONTENT_TYPES.COUPON]: { name: '优惠券管理', path: ['首页', '促销管理', '优惠券'] },
  [CONTENT_TYPES.SETTINGS]: { name: '系统设置', path: ['首页', '系统设置'] },
  [CONTENT_TYPES.SCHEDULE]: { name: '课程排班', path: ['首页', '课程排班'] }
};

export default function Logins() {
  const [currentContent, setCurrentContent] = useState(CONTENT_TYPES.STUDENT);
  const [currentUser, setCurrentUser] = useState(null);
  const [userPermissions, setUserPermissions] = useState(null);
  
  useEffect(() => {
    const userData = localStorage.getItem('currentUser');
    if (userData) {
      const user = JSON.parse(userData);
      setCurrentUser(user);
      
      // 获取用户权限
      const permissions = getUserPermissions(user.id);
      setUserPermissions(permissions);
      
      // 根据权限设置默认页面
      if (permissions) {
        if (permissions.role === '教师') {
          setCurrentContent(CONTENT_TYPES.HOME); // 教师默认显示首页
        } else {
          setCurrentContent(CONTENT_TYPES.HOME); // 超级管理员默认显示首页
        }
      }
    }
  }, []);
  // 用户下拉菜单
  const userMenu = [
    {
      key: 'profile',
      label: '个人资料'
    },
    {
      key: 'settings',
      label: '设置'
    },
    {
      type: 'divider'
    },
    {
      key: 'logout',
      label: '退出登录'
    }
  ];

  // 处理用户菜单点击
  const handleUserMenuClick = ({ key }) => {
    switch (key) {
      case 'profile':
        message.info('个人资料功能待实现');
        break;
      case 'settings':
        setCurrentContent(CONTENT_TYPES.SETTINGS);
        break;
      case 'logout':
        // 清除本地存储的用户信息
        localStorage.removeItem('currentUser');
        localStorage.removeItem('token');
        message.success('已成功退出登录');
        // 跳转到登录页面
        window.location.href = '/logins';
        break;
      default:
        break;
    }
  };

  // 渲染面包屑
  const renderBreadcrumb = () => {
    const current = BREADCRUMB_MAP[currentContent];
    return (
      <Breadcrumb 
        style={{ margin: '16px 0' }}
        items={current.path.map((item, index) => ({
          key: index,
          title: item
        }))}
      />
    );
  };

  // 渲染内容区域
  const renderContent = () => {
    // 检查页面访问权限
    if (!checkPagePermission(currentUser?.id, currentContent)) {
      return (
        <Result
          status="403"
          title="403"
          subTitle="抱歉，您没有权限访问此页面。"
          extra={
            <Button type="primary" onClick={() => setCurrentContent(CONTENT_TYPES.STUDENT)}>
              返回有权限的页面
            </Button>
          }
        />
      );
    }

    switch (currentContent) {
      case CONTENT_TYPES.HOME:
        return <Dashboard />;
      case CONTENT_TYPES.COURSE:
        return (
          <>
            {/* <Title level={3} className={styles.pageTitle}></Title> */}
            <Card variant="borderless">
              <Course/>
            </Card>
          </>
        );
      case CONTENT_TYPES.STUDENT:
        return <Student />;
      case CONTENT_TYPES.TEACHER:
        return (
          <>
            {/* <Title level={3} className={styles.pageTitle}>讲师</Title> */}
            <Card variant="borderless">
              <Teacher/>
            </Card>
          </>
        );
      case CONTENT_TYPES.ORDERS:
        return <OrderManagement />;
      case CONTENT_TYPES.REFUNDS:
        return (
          <>
            {/* <Title level={3} className={styles.pageTitle}>退款</Title> */}
            <Card variant="borderless">
              <p>退款管理内容</p>
            </Card>
          </>
        );
      case CONTENT_TYPES.BANNER:
        return (
          <>
            {/* <Title level={3} className={styles.pageTitle}>轮播图</Title> */}
            <Card variant="borderless">
              <p>轮播图管理内容</p>
            </Card>
          </>
        );
      case CONTENT_TYPES.ARTICLE:
        return (
          <>
            {/* <Title level={3} className={styles.pageTitle}>文章</Title> */}
            <Card variant="borderless">
              <p>文章管理内容</p>
            </Card>
          </>
        );
      case CONTENT_TYPES.FLASH_SALE:
        return (
          <>
            {/* <Title level={3} className={styles.pageTitle}>秒杀活动</Title> */}
            <Card variant="borderless">
              <p>秒杀活动管理内容</p>
            </Card>
          </>
        );
      case CONTENT_TYPES.COUPON:
        return (
          <>
            {/* <Title level={3} className={styles.pageTitle}>优惠券</Title> */}
            <Card variant="borderless">
              <p>优惠券管理内容</p>
            </Card>
          </>
        );
      case CONTENT_TYPES.SETTINGS:
        return <SystemSettings />;
      case CONTENT_TYPES.SCHEDULE:
        return <Schedule />;
      default:
        return null;
    }
  };

  return (
    <Layout style={{ minHeight: '100vh' }}>
      {/* 顶部导航栏 */}
      <Header className={styles.header}>
        <div className={styles.headerTitle}>
          教育后台管理系统
        </div>
        
                 <div className={styles.headerRight}>
           <Badge count={6} size="small">
             <BellOutlined className={styles.notificationIcon} />
           </Badge>
           <UserAddOutlined className={styles.userIcon} />
           <Dropdown menu={{ items: userMenu, onClick: handleUserMenuClick }} trigger={['click']}>
             <Space className={styles.userDropdown}>
               <span>{currentUser?.username || '未登录用户'}</span>
               {userPermissions && (
                 <span style={{ fontSize: '12px', color: '#ccc' }}>
                   ({userPermissions.role})
                 </span>
               )}
               <DownOutlined />
             </Space>
           </Dropdown>
         </div>
      </Header>
      
      <Layout>
                 {/* 左侧边栏 */}
         <Sider width={200} className={styles.sider}>
           <Menu
             mode="inline"
             selectedKeys={[currentContent]}
             defaultOpenKeys={['order', 'user', 'news', 'promotion']}
             className={styles.menu}
             theme="dark"
             onClick={({ key }) => setCurrentContent(key)}
           >
             {/* 首页 - 只有超级管理员可以访问 */}
             {checkPagePermission(currentUser?.id, CONTENT_TYPES.HOME) && (
               <Menu.Item key={CONTENT_TYPES.HOME} icon={<HomeOutlined />}>
                 首页
               </Menu.Item>
             )}
             
             {/* 课程管理 - 所有角色都可以访问 */}
             <Menu.Item key={CONTENT_TYPES.COURSE} icon={<BookOutlined />}>
               课程管理
             </Menu.Item>
             
             {/* 订单管理 - 只有超级管理员可以访问 */}
             {checkPagePermission(currentUser?.id, CONTENT_TYPES.ORDERS) && (
               <SubMenu key="order" icon={<ShoppingCartOutlined />} title="订单管理">
                 <Menu.Item key={CONTENT_TYPES.ORDERS}>订单</Menu.Item>
                 <Menu.Item key={CONTENT_TYPES.REFUNDS}>退款</Menu.Item>
               </SubMenu>
             )}
             
             {/* 用户管理 */}
             <SubMenu key="user" icon={<UserOutlined />} title="用户管理">
               <Menu.Item key={CONTENT_TYPES.STUDENT} icon={<TeamOutlined />}>
                 学员
               </Menu.Item>
               <Menu.Item key={CONTENT_TYPES.TEACHER} icon={<SolutionOutlined />}>讲师</Menu.Item>
             </SubMenu>
             
             {/* 资讯管理 - 只有超级管理员可以访问 */}
             {checkPagePermission(currentUser?.id, CONTENT_TYPES.BANNER) && (
               <SubMenu key="news" icon={<FileTextOutlined />} title="资讯管理">
                 <Menu.Item key={CONTENT_TYPES.BANNER}>轮播图</Menu.Item>
                 <Menu.Item key={CONTENT_TYPES.ARTICLE}>文章</Menu.Item>
               </SubMenu>
             )}
             
             {/* 促销管理 - 只有超级管理员可以访问 */}
             {checkPagePermission(currentUser?.id, CONTENT_TYPES.FLASH_SALE) && (
               <SubMenu key="promotion" icon={<GiftOutlined />} title="促销管理">
                 <Menu.Item key={CONTENT_TYPES.FLASH_SALE}>秒杀活动</Menu.Item>
                 <Menu.Item key={CONTENT_TYPES.COUPON}>优惠券</Menu.Item>
               </SubMenu>
             )}
             
             {/* 课程排班 - 教师可以访问 */}
             {checkPagePermission(currentUser?.id, CONTENT_TYPES.SCHEDULE) && (
               <Menu.Item key={CONTENT_TYPES.SCHEDULE} icon={<CalendarOutlined />}>
                 课程排班
               </Menu.Item>
             )}
             
             {/* 系统设置 - 只有超级管理员可以访问 */}
             {checkPagePermission(currentUser?.id, CONTENT_TYPES.SETTINGS) && (
               <Menu.Item key={CONTENT_TYPES.SETTINGS} icon={<SettingOutlined />}>
                 系统设置
               </Menu.Item>
             )}
           </Menu>
         </Sider>
        
        {/* 右侧内容区域 */}
        <Layout style={{ padding: '0 24px 24px' }}>
          {/* 面包屑导航 */}
          {renderBreadcrumb()}
          
          <Content className={styles.content}>
            {renderContent()}
          </Content>
        </Layout>
      </Layout>
    </Layout>
  );
}